package util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;

import models.Picture;
import play.Play;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.StorageClass;

public class S3PhotoUtil {
	private static final AmazonS3 s3client;
	public static final String BUCKET_NAME;

	private static final Map<String,Boolean> bucketMap = new LinkedHashMap<String,Boolean>();

    static {
        Configuration config = Configuration.getInstance();
		AWSCredentials creds = new BasicAWSCredentials(config.getProperty("accessKey"), 
				config.getProperty("secretKey"));
		s3client = new AmazonS3Client(creds);
		BUCKET_NAME = "indoordelivery"; 
	}

    public static void storePhoto (Picture picture) {
        storePublic(picture, false);
    }
	
    public static void storePublic (Picture picture, boolean reducedRedundancy) {
		store(picture, reducedRedundancy, CannedAccessControlList.PublicRead);
	}

	public static void store(Picture obj, boolean reducedRedundancy, CannedAccessControlList acl) {
		checkForAndCreateBucket();

		ObjectMetadata omd = new ObjectMetadata();
		omd.setContentType(obj.getMimeType());
		omd.setContentLength(obj.getData().length);

		ByteArrayInputStream is = new ByteArrayInputStream(obj.getData());
		PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, obj.getPath(), is, omd);

		if (reducedRedundancy) {
			request.setStorageClass(StorageClass.ReducedRedundancy);
		}

		s3client.putObject(request);

		if (acl != null) {
			s3client.setObjectAcl(BUCKET_NAME, obj.getPath(), acl);
		}

	}

	private static void checkForAndCreateBucket() {
		if (bucketMap.containsKey(BUCKET_NAME) == false
				&& s3client.doesBucketExist(BUCKET_NAME) == false) {
			s3client.createBucket(BUCKET_NAME);
		}
		bucketMap.put(BUCKET_NAME, true);
	}
}
